<template>
    <div class="order-complaint-management">
        <!-- 操作栏 -->
        <div class="operation-bar">
            <el-input
                v-model="searchText"
                placeholder="搜索投诉记录"
                style="width: 300px"
                clearable
            >
                <template #prefix>
                    <span style="margin-right: 8px">🔍</span>
                </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">
                <span style="margin-right: 5px">+</span>新增投诉记录
            </el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="filteredComplaints" border style="width: 100%">
            <el-table-column prop="orderId" label="订单编号" width="180" sortable />
            <el-table-column prop="buyerName" label="买家姓名" width="120" />
            <el-table-column prop="productName" label="商品名称" width="180" />
            <el-table-column prop="complaintType" label="投诉类型" width="150">
                <template #default="{ row }">
                    {{ complaintTypeOptions.find(t => t.value === row.complaintType)?.label }}
                </template>
            </el-table-column>
            <el-table-column prop="complaintDate" label="投诉时间" width="150">
                <template #default="{ row }">
                    {{ formatDate(row.complaintDate) }}
                </template>
            </el-table-column>
            <el-table-column prop="complaintContent" label="投诉内容" width="200">
                <template #default="{ row }">
                    <span v-if="row.complaintContent.length > 20">{{ row.complaintContent.slice(0, 20) }}...</span>
                    <span v-else>{{ row.complaintContent }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="处理状态" width="120">
                <template #default="{ row }">
                    <el-tag :type="statusType[row.status]">
                        {{ statusOptions.find(s => s.value === row.status)?.label }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="isEditMode ? '编辑投诉记录' : '新增投诉记录'"
            width="600"
        >
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="80px"
            >
                <el-form-item label="订单编号" prop="orderId">
                    <el-input v-model="formData.orderId" :disabled="isEditMode" />
                </el-form-item>
                <el-form-item label="买家姓名" prop="buyerName">
                    <el-input v-model="formData.buyerName" />
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model="formData.productName" />
                </el-form-item>
                <el-form-item label="投诉类型" prop="complaintType">
                    <el-select v-model="formData.complaintType" placeholder="请选择投诉类型">
                        <el-option
                            v-for="item in complaintTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="投诉时间" prop="complaintDate">
                    <el-date-picker
                        v-model="formData.complaintDate"
                        type="datetime"
                        placeholder="选择日期时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </el-form-item>
                <el-form-item label="投诉内容" prop="complaintContent">
                    <el-input type="textarea" v-model="formData.complaintContent" rows="3" />
                </el-form-item>
                <el-form-item label="处理状态" prop="status">
                    <el-select v-model="formData.status" placeholder="请选择处理状态">
                        <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 日期格式化（包含时间）
const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    }).replace(/\//g, '-')
}

// 投诉类型选项（根据网页2鲜花行业常见投诉类型优化）
const complaintTypeOptions = [
    { value: 'quality', label: '花材质量问题' },
    { value: 'description', label: '描述不符' },
    { value: 'shipping', label: '配送问题' },
    { value: 'freshness', label: '保鲜问题' },
    { value: 'service', label: '服务态度' }
]

// 处理状态选项（根据网页4投诉处理流程优化）
const statusOptions = [
    { value: 0, label: '待处理' },
    { value: 1, label: '处理中' },
    { value: 2, label: '已解决' }
]
const statusType = { 0: 'danger', 1: 'warning', 2: 'success' }

// 10条鲜花投诉测试数据（基于网页2、4的常见投诉场景）
const complaints = ref([
    {
        id: 1,
        orderId: 'FLW2024001',
        buyerName: '王女士',
        productName: '红玫瑰礼盒',
        complaintType: 'freshness',
        complaintDate: '2024-05-15 14:30:00',
        complaintContent: '玫瑰花收到时已枯萎，花瓣出现严重褐变',
        status: 0
    },
    {
        id: 2,
        orderId: 'FLW2024002',
        buyerName: '张先生',
        productName: '香槟玫瑰花束',
        complaintType: 'description',
        complaintDate: '2024-05-16 10:15:00',
        complaintContent: '实际花束尺寸比宣传图小30%，包装材料不符',
        status: 1
    },
    {
        id: 3,
        orderId: 'FLW2024003',
        buyerName: '李女士',
        productName: '向日葵花篮',
        complaintType: 'shipping',
        complaintDate: '2024-05-17 15:45:00',
        complaintContent: '配送延误36小时导致花材脱水严重',
        status: 2
    },
    {
        id: 4,
        orderId: 'FLW2024004',
        buyerName: '赵先生',
        productName: '郁金香花束',
        complaintType: 'quality',
        complaintDate: '2024-05-18 09:30:00',
        complaintContent: '郁金香茎部有虫蛀痕迹，花瓣残缺',
        status: 0
    },
    {
        id: 5,
        orderId: 'FLW2024005',
        buyerName: '陈女士',
        productName: '满天星干花',
        complaintType: 'description',
        complaintDate: '2024-05-19 16:20:00',
        complaintContent: '实际颜色与页面展示的雾蓝色差异明显',
        status: 1
    },
    {
        id: 6,
        orderId: 'FLW2024006',
        buyerName: '周先生',
        productName: '百合花束',
        complaintType: 'freshness',
        complaintDate: '2024-05-20 11:00:00',
        complaintContent: '百合花苞未开放即出现腐烂现象',
        status: 2
    },
    {
        id: 7,
        orderId: 'FLW2024007',
        buyerName: '吴女士',
        productName: '绣球花礼盒',
        complaintType: 'shipping',
        complaintDate: '2024-05-21 17:10:00',
        complaintContent: '配送过程中包装破损导致花材变形',
        status: 0
    },
    {
        id: 8,
        orderId: 'FLW2024008',
        buyerName: '郑先生',
        productName: '混合花束',
        complaintType: 'service',
        complaintDate: '2024-05-22 08:45:00',
        complaintContent: '客服拒绝处理漏送配花的问题',
        status: 1
    },
    {
        id: 9,
        orderId: 'FLW2024009',
        buyerName: '孙女士',
        productName: '永生花礼盒',
        complaintType: 'quality',
        complaintDate: '2024-05-23 13:30:00',
        complaintContent: '永生花表面出现霉斑，保存不当',
        status: 2
    },
    {
        id: 10,
        orderId: 'FLW2024010',
        buyerName: '林先生',
        productName: '婚礼鲜花布置',
        complaintType: 'shipping',
        complaintDate: '2024-05-24 14:00:00',
        complaintContent: '延迟送达导致婚礼现场布置未完成',
        status: 0
    }
])

// 搜索功能（支持多字段模糊搜索）
const searchText = ref('')
const filteredComplaints = computed(() => {
    const searchKey = searchText.value.toLowerCase()
    return complaints.value.filter(complaint => {
        return [
            complaint.orderId,
            complaint.buyerName,
            complaint.productName,
            complaint.complaintContent,
            complaintTypeOptions.find(t => t.value === complaint.complaintType)?.label
        ].join('').toLowerCase().includes(searchKey)
    })
})

// 对话框状态管理
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
    id: null,
    orderId: '',
    buyerName: '',
    productName: '',
    complaintType: 'quality',
    complaintDate: new Date().toISOString().split('.')[0],
    complaintContent: '',
    status: 0
})

// 表单验证规则（根据网页2、4的投诉处理规范增强）
const formRules = {
    orderId: [
        { required: true, message: '请输入订单编号', trigger: 'blur' },
        { pattern: /^FLW\d{8}$/, message: '格式示例：FLW20240518' }
    ],
    buyerName: [
        { required: true, message: '请输入买家姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '姓名长度2-10个字符' }
    ],
    productName: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 4, max: 20, message: '名称长度4-20个字符' }
    ],
    complaintType: [{ required: true, message: '请选择投诉类型', trigger: 'change' }],
    complaintDate: [{ required: true, message: '请选择投诉时间', trigger: 'change' }],
    complaintContent: [
        { required: true, message: '请填写投诉内容', trigger: 'blur' },
        { min: 10, max: 200, message: '内容长度10-200个字符' }
    ],
    status: [{ required: true, message: '请选择处理状态', trigger: 'change' }]
}

// 操作函数（根据网页4投诉处理流程优化）
const handleAdd = () => {
    isEditMode.value = false
    resetForm()
    dialogVisible.value = true
}

const handleEdit = (row) => {
    isEditMode.value = true
    Object.assign(formData, { ...row })
    dialogVisible.value = true
}

const handleDelete = (id) => {
    ElMessageBox.confirm('确定删除该投诉记录？删除后将不可恢复！', '警告', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消操作',
        type: 'warning'
    }).then(() => {
        complaints.value = complaints.value.filter(c => c.id !== id)
        ElMessage.success('投诉记录已删除')
    })
}

const submitForm = async () => {
    await formRef.value.validate()
    if (isEditMode.value) {
        const index = complaints.value.findIndex(c => c.id === formData.id)
        complaints.value.splice(index, 1, { ...formData })
    } else {
        complaints.value.push({
            ...formData,
            id: Date.now(),
            complaintDate: formData.complaintDate || new Date().toISOString().split('.')[0]
        })
    }
    dialogVisible.value = false
}

const resetForm = () => {
    formData.id = null
    formData.orderId = ''
    formData.buyerName = ''
    formData.productName = ''
    formData.complaintType = 'quality'
    formData.complaintDate = new Date().toISOString().split('.')[0]
    formData.complaintContent = ''
    formData.status = 0
}
</script>

<style scoped>
.order-complaint-management {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.operation-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
}

.el-table {
    margin-top: 20px;
}

.el-tag {
    font-weight: 500;
}

.el-textarea__inner {
    height: 80px;
}
</style>